package ext.tianma.part.util.updateIBAValues;

import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.rmi.RemoteException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.apache.poi.POIXMLDocument;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import ext.com.core.CoreUtil;
import ext.tianma.bom.util.GenericUtil;
import ext.tianma.part.PartWorkflowUtil;
import ext.tianma.part.resolution.Resolution;
import wt.fc.Persistable;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.collections.WTArrayList;
import wt.lifecycle.LifeCycleHelper;
import wt.lifecycle.State;
import wt.part.WTPart;
import wt.part.WTPartMaster;
import wt.part.WTPartStandardConfigSpec;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import wt.vc.config.ConfigHelper;
import wt.vc.views.View;
import wt.vc.views.ViewHelper;

public class updatePartIbaValues {

	public static String STATUTE_PATH = "/ptc/Windchill/codebase/ext/tianma/part/config/resolution1.xlsx";
	public static String STATUTE_PATH1 = "/ptc/Windchill/codebase/ext/tianma/part/config/sendToERP.xlsx";

	/***
	 * 读取exce分辨率及分辨率代码
	 * 
	 * @return
	 * @throws WTException
	 */
	public static void getCascade() throws WTException {

		System.out.println("===>>start==>>action===>>");
		InputStream is = null;
		Workbook wb = null;
		Workbook workbook = null;
		try {
			System.out.println("CASCADE_PATH===>>" + STATUTE_PATH);
			is = new FileInputStream(STATUTE_PATH);

			System.out.println("=====>>>" + STATUTE_PATH);
			if (!is.markSupported()) {
				is = new PushbackInputStream(is, 8);
			}

			if (POIFSFileSystem.hasPOIFSHeader(is)) {
				// 2003及以下
				wb = new HSSFWorkbook(is);
			} else if (POIXMLDocument.hasOOXMLHeader(is)) {
				// 2007及以上
				wb = new XSSFWorkbook(is);
			} else {
				// 不是Excel
				throw new WTException("Incorrect configuration file path.");
			}

			workbook = wb;

			Sheet sheet = workbook.getSheetAt(0);
			Row row;
			Cell cell1, cell2, cell;
			String tempVal;

			Map<String, String> fblMap = new HashMap<String, String>();
			// 第一行为表头，从第二行开始遍历
			for (int i = 2, rowNum = sheet.getLastRowNum(); i <= rowNum; i++) {
				if ((row = sheet.getRow(i)) != null) {
					// 遍历列
					String PartNUmber = "";
					String fbl_W = "";
					int cellNum = row.getLastCellNum();
					String str = "";
					for (int j = 0; j <= cellNum; j++) {
						cell = row.getCell(j);
						cell1 = row.getCell(0);
						if (cell1 == null || (tempVal = cell1.getStringCellValue()) == null) {
							str = "";
						} else {
							PartNUmber = cell1.getStringCellValue();
							System.out.println("PartNUmber====>>>" + PartNUmber);
							WTArrayList partList = new WTArrayList();
							// 获取design试图
							WTPart part = getWTPartByNumberAndView(PartNUmber, "Design");
							if (part != null) {
								partList = PartWorkflowUtil.getAllPartViews(part);// 获取所有视图
								System.out.println("partList===>>" + partList.size());
								part = CoreUtil.getWTPartByNumberAndView(part.getNumber(), "Design");
								part = (WTPart) GenericUtil.checkout(part);
								System.out.println("==检出  ====   ");
								System.out.println("partNumber===>>" + part.getNumber() + ":::PartView==>>"
										+ part.getViewName());
								GenericUtil.checkin(part);
								System.out.println("==检入 ====   ");
								ext.generic.erp.service.PartReleaseService.releasePersistable(partList,
										ext.generic.erp.common.CommonUtil.getCurrentTime());

							}
						}
					}
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw new WTException(e);
		} catch (IOException e) {
			e.printStackTrace();
			throw new WTException(e);
		} catch (WTPropertyVetoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			close(is);
		}
	}

	public static void updateIbaValue() {
		String PartNUmber = "TM057JVHS02-00";
		WTPart part;
		try {
			part = getWTPartByNumberAndView(PartNUmber, "Design");

			if (part != null) {
				
				part = (WTPart) GenericUtil.checkout(part);
				// if
				System.out.println("==检出  ====   ");
				//
				System.out.println("partNumber===>>" + part.getNumber() + ":::PartView==>>" + part.getViewName());

				Resolution.setAttsToIBA(part);
				GenericUtil.checkin(part);
				part = (WTPart) PersistenceHelper.manager.refresh(part);
				System.out.println("==检入 ====   ");
			}
		} catch (WTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (WTPropertyVetoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	public static void getCascadeToSendERP(String state) throws WTException {

		System.out.println("===>>start==>>action===>>");
		InputStream is = null;
		Workbook wb = null;
		Workbook workbook = null;
		try {
			System.out.println("CASCADE_PATH===>>" + STATUTE_PATH1);
			is = new FileInputStream(STATUTE_PATH1);

			System.out.println("=====>>>" + STATUTE_PATH1);
			if (!is.markSupported()) {
				is = new PushbackInputStream(is, 8);
			}

			if (POIFSFileSystem.hasPOIFSHeader(is)) {
				// 2003及以下
				wb = new HSSFWorkbook(is);
			} else if (POIXMLDocument.hasOOXMLHeader(is)) {
				// 2007及以上
				wb = new XSSFWorkbook(is);
			} else {
				// 不是Excel
				throw new WTException("Incorrect configuration file path.");
			}

			workbook = wb;

			Sheet sheet = workbook.getSheetAt(0);
			Row row;
			Cell cell1;

			Map<String, String> fblMap = new HashMap<String, String>();
			// 第一行为表头，从第二行开始遍历
			for (int i = 2, rowNum = sheet.getLastRowNum(); i <= rowNum; i++) {
				if ((row = sheet.getRow(i)) != null) {
					// 遍历列
					String PartNUmber = "";
					int cellNum = row.getLastCellNum();
					for (int j = 0; j <= cellNum; j++) {
						cell1 = row.getCell(0);
						if (cell1 == null) {
						} else {
							PartNUmber = cell1.getStringCellValue();
							System.out.println("PartNUmber====>>>" + PartNUmber);
							sendToERPS(PartNUmber,state);
						}
					}
				}
			}
			System.out.println("================   send sucessful  ===============");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw new WTException(e);
		} catch (IOException e) {
			e.printStackTrace();
			throw new WTException(e);
		} finally {
			close(is);
		}
	}

	

	public static void sendToERPS(String PartNUmber,String state) {
		WTArrayList partList = new WTArrayList();
		WTPart part;
		try {
			part = getWTPartByNumberAndView(PartNUmber, "Design");
			if (part != null) {
				partList = PartWorkflowUtil.getAllPartViews(part);// 获取所有视图
				partList.add(part);
				//刷新物料状态为废弃
				int size = partList.size() ;
				for(int i = 0 ; i < size ; i++ ){
					Persistable persistable = partList.getPersistable(i) ;
					
					if( persistable != null && persistable instanceof WTPart ){
						WTPart partByView = ( WTPart ) persistable ;
						System.out.println("partByView=====>>"+partByView.getNumber());
						System.out.println("partState=====>>"+partByView.getLifeCycleState().getDisplay(Locale.CHINA));
						LifeCycleHelper.service.setLifeCycleState(partByView, State.toState("OBSOLESCENCE"));
						PersistenceHelper.manager.refresh(partByView);
						System.out.println("====设置完成=====");
					}
					
				}
//				System.out.println("partList===>>"+partList.size());
//				System.out.println("partNumber===>>" + part.getNumber() + ":::PartView==>>" + part.getViewName());
//				ext.generic.erp.service.PartReleaseService.releasePersistable(partList,
//						 ext.generic.erp.common.CommonUtil.getCurrentTime());
			}
		} catch (WTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}

	/**
	 * 关闭资源
	 * 
	 * @param closeable
	 */
	public static void close(Closeable closeable) {
		try {
			if (closeable != null) {
				closeable.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 通过编号查找部件
	 * 
	 * @param number
	 * @return
	 * @throws WTException
	 */
	public static WTPart findWTPartByNumber(String number) throws WTException {
		QuerySpec qs = new QuerySpec(WTPart.class);
		qs.appendWhere(new SearchCondition(WTPart.class, WTPart.LATEST_ITERATION, SearchCondition.IS_TRUE), 0);
		qs.appendAnd();
		qs.appendWhere(new SearchCondition(WTPart.class, WTPart.NUMBER, SearchCondition.EQUAL, number));
		QueryResult qr = PersistenceHelper.manager.find(qs);
		return qr.hasMoreElements() ? (WTPart) qr.nextElement() : null;
	}

	/**
	 * 根据编号和视图查询对应最新视图版本的零部件.
	 * 
	 * @author Harry Cao
	 * @param number
	 * @param view
	 * @return
	 * @throws WTException
	 */
	public static WTPart getWTPartByNumberAndView(String number, String view) throws WTException {
		WTPartMaster master = getWTPartMasterByNumber(number);
		if (master == null)
			return null;
		else
			return getWTPartByMasterAndView(master, view);
	}

	/**
	 * 根据零部件的编号查找零部件的主数据(master)
	 * 
	 * @author Harry Cao
	 * @param partNumber
	 * @return
	 * @throws WTException
	 */
	public static WTPartMaster getWTPartMasterByNumber(String partNumber) throws WTException {
		WTPartMaster master = null;
		QuerySpec qs = null;
		QueryResult qr = null;
		qs = new QuerySpec(WTPartMaster.class);
		// 定义搜索条件，以零部件编号方式在master中搜索
		SearchCondition sc = new SearchCondition(WTPartMaster.class, WTPartMaster.NUMBER, SearchCondition.EQUAL,
				partNumber);
		qs.appendSearchCondition(sc);
		qr = PersistenceHelper.manager.find(qs);
		if (qr.hasMoreElements()) {
			master = (WTPartMaster) qr.nextElement();
		}
		return master;
	}

	/**
	 * 根据零部件主数据(master)和视图获取对应最新版本零部件
	 * 
	 * @author Harry Cao
	 * @param master
	 * @param view
	 * @return
	 * @throws WTException
	 */
	public static WTPart getWTPartByMasterAndView(WTPartMaster master, String view) throws WTException {
		WTPart part = null;
		// 根据视图名称获取视图对象
		View viewObj = ViewHelper.service.getView(view);

		// 根据视图构造产品结构配置规范
		WTPartStandardConfigSpec standardConfig = WTPartStandardConfigSpec.newWTPartStandardConfigSpec(viewObj, null);
		try {
			standardConfig.setView(viewObj);
		} catch (WTPropertyVetoException wpve) {
			throw new WTException(wpve);
		}

		// 根据master和视图获取对应最新的视图版本零部件
		QueryResult qr1 = ConfigHelper.service.filteredIterationsOf(master, standardConfig);
		if (qr1.hasMoreElements()) {
			part = (WTPart) qr1.nextElement();
			if (!part.getViewName().equals(view))
				return null;
			System.out.println("部件的视图：" + part.getViewName());
		}

		return part;
	}

}
